<style lang='scss' type='stylesheet/scss' scoped>
</style>

<template>
  <div class="as-checkbox"
       :class="[...classNames,...[this.size ? 'as-checkbox--' + this.size : '']]"
       @click="disabled?'':model=!model">
    <div class="as-checkbox__input">
      <div class="as-checkbox__inner"
           :class="classNames"></div>
      <input type="checkbox"
             v-model="model"
             hidden>
    </div>
    <div class="as-checkbox__label"
         :class="classNames">
      <slot v-if="$slots&&$slots.default"></slot>
      <span v-else>{{label}}</span>
    </div>
  </div>
</template>

<script type='text/ecmascript-6'>
import emitter from "../../../mixin";
export default {
  name: "AsCheckbox",
  props: {
    value: {},
    disabled: Boolean,
    border: Boolean,
    label: {},
    indeterminate: Boolean,
    size: String
  },
  mixins: [emitter],
  computed: {
    isGroup() {
      let parent = this.$parent;

      while (parent) {
        if (parent.$options.componentName === "AsCheckboxGroup") {
          this._checkboxGroup = parent;
          return true;
        } else {
          parent = parent.$parent;
        }
      }

      return false;
    },
    classNames() {
      return [
        {
          "is-checked": this.isGroup ? this.model : this.value,
          "is-disabled": this.disabled,
          "is-border": this.border,
          "is-indeterminate": this.model ? false : this.indeterminate
        }
      ];
    },
    model: {
      get() {
        return this.isGroup
          ? this._checkboxGroup.value.includes(this.label)
          : this.value;
      },
      set(val) {
        if (this.isGroup) {
          this.dispatch("AsCheckboxGroup", "handlerChange", [this.label]);
        } else {
          this.$emit("input", val);
          this.$emit("change", val);
        }
      }
    }
  },
  data() {
    return {
      _checkboxGroup: {}
    };
  }
};
</script>
